﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using PccCommonForC;
using System.Drawing;

public partial class Manager_Import_ImportFilm : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["AdminUserID"] == null)
        {
            Response.Write("<script language=javascript>alert('Time is out.');window.open('../Default.aspx','_top');</script>");
            return;
        }
    }
    private bool CheckFileUpload(string sFileName)
    {
        bool b = false;//not ok
        string FileTypeExcept = ConfigurationManager.AppSettings["FileExcept"];
        string sFileType = GetFileType(sFileName);

        string[] arr = FileTypeExcept.Split(';');
        for (int i = 0; i < arr.Length; i++)
        {
            if (arr[i].ToUpper().Trim() == sFileType.ToUpper().Trim())
            {
                b = true;
                break;
            }
        }

        return b;
    }
    private string GetFileType(string sFileName)
    {
        string[] arr = sFileName.Split('.');
        if (arr.Length > 1)
        {
            return arr[arr.Length - 1];
        }
        return "";
    }
    private bool CheckDecimal(string value)
    {
        bool b = true;//is a number
        try
        {
            decimal.Parse(value);
        }
        catch (Exception ex)
        {
            b = false;
        }
        return b;
    }
    protected bool CheckYYYYMM(string s)
    {
        bool b = true;//valid format yyyymm

        if (s.Length > 6 || s.Length < 6)
            b = false;
        else if (!CheckDecimal(s))
            b = false;


        return b;
    }
    protected void btnImport_Click(object sender, EventArgs e)
    {
        tblOutput.Rows.Clear();
        string sFullFileName = "", sFileName = "", sFilePath = "", sSheetName = "forecast", sFileExcept = "xls", sSheetRange = "";
        sFullFileName = fileForecast.PostedFile.FileName;

        sSheetName = ConfigurationManager.AppSettings["SheetName"].ToString();
        sFileExcept = ConfigurationManager.AppSettings["FileExcept"].ToString();
        sSheetRange = ConfigurationManager.AppSettings["SheetRange"].ToString();
        //read picture size
        int len = fileForecast.PostedFile.ContentLength;
        //get file name
        sFullFileName = fileForecast.PostedFile.FileName;

        bool b = CheckFileUpload(sFullFileName);
        if (!b)
        {
            ShowMessage("Chon file Excel");
            return;
        }

        sFileName = sFullFileName.Substring(sFullFileName.LastIndexOf("\\") + 1);

        sFilePath = Server.MapPath(ConfigurationManager.AppSettings["ExcelPath"].ToString().Trim());
        sFilePath = sFilePath + "\\" + sFileName;
        bool bExist = System.IO.File.Exists(sFilePath);
        if (bExist)
        {
            try
            {
                System.IO.File.Delete(sFilePath);
            }
            catch (System.IO.IOException ex)
            {
                //ShowMessage(ex.Message.ToString());
            }
            catch (UnauthorizedAccessException uax)
            {
                // ShowMessage(uax.Message.ToString());
            }
        }

        try
        {
            fileForecast.PostedFile.SaveAs(sFilePath);
        }
        catch (System.IO.IOException ex)
        {
            //ShowMessage(ex.Message.ToString());
        }
        catch (UnauthorizedAccessException uax)
        {
            //ShowMessage(uax.Message.ToString());
        }
        catch (Exception ex)
        {
            //ShowMessage(ex.Message.ToString());
        }

        /**/
        clsWebShop cls = new clsWebShop();
        CExcel oExc = new CExcel(sFilePath, sSheetName, sSheetRange);
        DataTable dtExcel = new DataTable();
        try
        {
            DataTable dtSrc = new DataTable();

            dtExcel = oExc.Read();
            if (dtExcel.Rows.Count > 0)
            {
                PccMsg msgOut = new PccMsg();
                DataColumnCollection columns = dtExcel.Columns;
                if (!columns.Contains("Ma phim") || !columns.Contains("Ten phim") || !columns.Contains("The Loai"))
                {
                    //Ten cot phai la"Art code","Model","Total"z
                    ShowMessage("Định dạng cột chưa chính xác");
                    return;
                }
                int iCount = 0, iImportRecord = 0;
                PccMsg msgErrors = new PccMsg();
                iCount = dtExcel.Rows.Count;

                AddHeader(tblOutput);
                TableCell cell;
                TableRow row;
                for (int i = 0; i < iCount; i++)
                {
                    int index = i + 1;
                    if (dtExcel.Rows[i].RowState != DataRowState.Deleted)
                    {
                        row = new TableRow();
                        string FilmEng="", CatNm="", FilmNo="";
                        decimal Capacity = 0;
                        try //Them du lieu
                        {

                            FilmEng = dtExcel.Rows[i]["Ten Phim"].ToString().Trim();
                            CatNm = dtExcel.Rows[i]["The Loai"].ToString();
                            FilmNo = dtExcel.Rows[i]["Ma Phim"].ToString();
                            Capacity = Math.Round(decimal.Parse(dtExcel.Rows[i]["Dung luong"].ToString()), 2);


                            PccMsg msg = new PccMsg();
                            msg.CreateFirstNode("FilmNo", FilmNo);
                            msg.CreateFirstNode("CatNm", CatNm);
                            msg.CreateFirstNode("FilmEng", FilmEng);
                            msg.CreateFirstNode("FilmVnd", dtExcel.Rows[i]["Ten Tieng Viet"].ToString());
                            msg.CreateFirstNode("FilmYear", dtExcel.Rows[i]["Nam Phat Hanh"].ToString());
                            msg.CreateFirstNode("ImgURL", "Images/Film/" + FilmEng + ".jpg");
                            msg.CreateFirstNode("Hero", dtExcel.Rows[i]["Dien vien"].ToString());
                            msg.CreateFirstNode("Director", dtExcel.Rows[i]["Dao Dien"].ToString());
                            msg.CreateFirstNode("National", dtExcel.Rows[i]["Quoc gia"].ToString());
                            msg.CreateFirstNode("Sound", dtExcel.Rows[i]["Am thanh"].ToString());
                            msg.CreateFirstNode("Subtitles", dtExcel.Rows[i]["Phu de"].ToString());
                            msg.CreateFirstNode("Capacity", Capacity.ToString());
                            msg.CreateFirstNode("Format", dtExcel.Rows[i]["Dinh dang"].ToString());
                            msg.CreateFirstNode("Content", dtExcel.Rows[i]["Noi Dung"].ToString());
                            msg.CreateFirstNode("UserID", Session["AdminUserID"].ToString());
                            string strXML = cls.ImportFilm(msg.GetXmlStr);
                            msg = new PccMsg(strXML);
                            string strOutput = msg.Query("strOutput");
                            if (strOutput == "0")
                                iImportRecord++;
                            string RowType = "";
                            strOutput = RptErrString(strOutput, ref RowType);
                            AddRow(row, RowType, index.ToString());
                            AddRow(row, RowType, FilmNo);
                            AddRow(row, RowType, strOutput);
                            AddRow(row, RowType, FilmEng);
                            AddRow(row, RowType, CatNm);
                            tblOutput.Rows.Add(row);

                        }
                        catch (Exception ex)
                        {
                            AddRow(row, "E", index.ToString());
                            AddRow(row, "E", FilmNo);
                            AddRow(row, "E", ex.ToString());
                            AddRow(row, "E", FilmEng);
                            AddRow(row, "E", CatNm);
                            tblOutput.Rows.Add(row);
                        }

                    }
                }

                lblTotal.Text = "Tổng số dòng được thêm vào : " + iImportRecord.ToString();

            }
        }
        catch (System.Data.OleDb.OleDbException ex)
        {
            ShowMessage(ex.Message.ToString());
        }

    }

    private void AddHeader(Table tbl)
    {
        TableCell cell;
        TableRow row = new TableRow();
        cell = new TableCell();
        cell.Width = Unit.Percentage(2);
        AddCell(row, cell, "No.");
        cell = new TableCell();
        cell.Width = Unit.Percentage(5);
        AddCell(row, cell, "Ma");
        cell = new TableCell();
        cell.Width = Unit.Percentage(40);
        AddCell(row, cell, "Trạng thái");
        cell = new TableCell();
        cell.Width = Unit.Percentage(40);
        AddCell(row, cell, "Tên");
        cell = new TableCell();
        cell.Width = Unit.Percentage(20);
        AddCell(row, cell, "Thể loại");
        row.BackColor = Color.BlueViolet;
        row.ForeColor = Color.White;
        row.HorizontalAlign = HorizontalAlign.Center;
        row.Font.Bold = true;
        row.Height = Unit.Pixel(30);
        tblOutput.Rows.Add(row);
    }

    private void AddCell(TableRow row, TableCell cell, string str)
    {
        cell.Text = str;
        cell.BorderWidth = 1;
        row.Cells.Add(cell);
    }

    private void AddRow(TableRow row, string str)
    {
        TableCell cell = new TableCell();
        cell.Text = str;
        cell.BorderWidth = 1;
        row.Cells.Add(cell);
    }

    private void AddRow(TableRow row, string RowType, string str)
    {
        TableCell cell = new TableCell();
        cell.Text = str;
        cell.BorderWidth = 1;
        row.Cells.Add(cell);
        FormatRowStyle(RowType, cell, row);
    }

    private void FormatRowStyle(string RowType, TableCell cell, TableRow row)
    {
        switch (RowType.ToUpper())
        {
            case "E":
                row.BackColor = Color.FromName("OrangeRed");
                cell.ForeColor = Color.White;
                break;
            case "S":
                row.BackColor = Color.FromName("#99ccff");
                cell.ForeColor = Color.FromName("#330066");
                break;
        }

    }

    private string RptErrString(string err, ref string RowType)
    {
        //Thanh cong:0
        //Bi loi:-1 SP,-2 Thuoc tinh,-3 Trung File
        string strReturn = "";
        switch (err)
        {
            case "-1":
                strReturn = "Lỗi trùng tên tiếng Anh";
                RowType = "E";
                break;
            case "-2":
                strReturn = "Lỗi trùng tên tiếng Việt";
                RowType = "E";
                break;
            case "-3":
                strReturn = "Không tồn tại thể loại";
                RowType = "E";
                break;
            case "-4":
                strReturn = "Lỗi trùng mã phim";
                RowType = "E";
                break;
            case "-100":
                strReturn = "Không thể thêm vào";
                RowType = "E";
                break;
            case "0":
                strReturn = "Success";
                RowType = "S";
                break;
        }
        return strReturn;
    }

    private void ShowMessage(string sMsg)
    {
        sMsg = sMsg.Replace("'", " ");
        sMsg = sMsg.Replace("\n", " ");
        Response.Write("<script>alert('" + sMsg + "')</script>");
    }
}
